<?php
namespace app\controller\model;

use app\BaseController;
use think\facade\Db;

class Gas extends BaseController
{
    public $gasID,$prices,$tables,$gas;
    public function __construct($gasID=0,$prices=[],$gas=[]){
		$this->gasID =  $gasID;
		$this->prices =  $prices;
		$this->gas =  $gas;
	    $this->tables = new Tables();
		if(!$this->prices) $this->getPrices();
		if(!$this->prices) return false;
    }
	public function SaveGasPrice($priceJson=""){
		$priceArr = json_decode($priceJson,true);
		if(!$priceArr)echojson([],1,'价格数据错误');
		if(count($priceArr) != count($this->prices))echojson([],1,'数据校验错误');
		lock();
		foreach ($this->prices as $k=>$v){
			$tail = json_decode($v['tail'],true);
			$oneArr = $priceArr[$k];
			if(count($oneArr) != 7)echojson([],1,'行数据校验错误');
			$tail['prices']=$oneArr;
			$v['tail']=json_encode($tail);
			DB::name($this->tables->gasPrice)->save($v);
		}
		echojson();
	}
	public function getGasPrice($end=false){
		$this->setGasPrice($end);
		return $this->prices;
	}
	public function getWeekPrice(){
		$nowWeek = date('w');
		foreach ($this->prices as &$v){
			$v['price_yfq'] = $v['prices'][$nowWeek+1];
		}
		return $this->prices;
	}
	protected function setGasPrice($end=false,$week=false){//获取减少价格
		foreach ($this->prices as &$v){
			$temArr = json_decode($v['tail'],true);
			if(!$temArr)$temArr=[];
			$v['prices']=[$v['oil_no']];//['92#',0.2,0.2,0.1,0.3,0.2,0.6,0.4] 周日到周六枪价基础上减少的
			if(isset($temArr['prices'])){
				foreach ($temArr['prices'] as $v2){
					$v['prices'][] = $end?bcsub($v['price_gun'],$v2,2):$v2;
				}
			}else{
				if(!$this->gas)$this->getGas();
				$rule = $this->gas['subPrice']<=0?r_rule2(271)['rule']:$this->gas['subPrice'];
				$rule = bcdiv($rule,100,2);
				$cha = bcsub($v['price_gun'],$v['price_yfq'],2);
				for ($i=0;$i<7;$i++){
					$chaPrice = bcmul($cha,$rule,2);
					$v['prices'][] = $end?bcsub($v['price_gun'],$chaPrice,2):$chaPrice;
				}
			}
		}
	}
	protected function getGas(){
		$this->gas = DB::name($this->tables->gas)->where("id",$this->gasID)->find();
	}
	protected function getPrices(){
		$this->prices = DB::name($this->tables->gasPrice)->where("gasID",$this->gasID)->where("status",1)->select()->toArray();
	}
}
?>